var spawn = require('child_process').spawn;
var net = require('net');
var fs = require('fs');
var socket;

function takePhoto (userOpenId) {
    var title = "demo";
    var param = [];
    param.push("-d");
    param.push("/dev/video0");
    param.push("-r");
    param.push("850*640");
    param.push("--no-title");
    param.push("--no-banner");
    param.push("--no-timestamp");
    param.push("/usr/local/photos/demo.jpg");
    var fswebcam = spawn('fswebcam' , param);
    fswebcam.on('exit' , function (code) {
        sendPhoto(userOpenId);
        fswebcam.kill();
    });
    fswebcam.on('error' , function () {
        fswebcam.kill();
    });
}
function sendPhoto (userOpenId) {
    var base64 = fs.readFileSync("demo.jpg").toString("base64");
    socket.write("0000" + base64.length + userOpenId + ":" + base64 , function () {
        console.log("photo data has been sent");
    });
}
function connectSocket () {
    socket = new net.Socket({
        readable : true ,
        writable : true ,
        allowHalfOpen : false
    });
    socket.connect(9999 , '121.41.160.43' , function () {
        socket.write("0000000017shopOpenId=100000" , function () {
            console.log("welcome to use snapshot,id has sent");
        });
    });
    socket.on('data' , function (data) {
        var command = data.toString();
        console.log("accept a command:" , command);
        if (/[a-zA-Z0-9]+:\d/gi.test(command)) {
            var userOpenId = command.split(':')[0];
            takePhoto(userOpenId);
        }
    });
    socket.on("close" , function () {
        console.log("closed : on,no,fuck,socket is closed!");
        socket.destroy();
        setTimeout(function () {
            connectSocket();
        } , 1000);
    });
    socket.on("error" , function (err) {
        console.log("error : oh,shit,there is a error occur,what to do?i don't know!!!" , err);
        socket.destroy();
        setTimeout(function () {
            connectSocket();
        } , 1000);
    });
    socket.on("end" , function () {
        console.log("end error : the server end do not want to play with you any more!!!");
        socket.destroy();
        setTimeout(function () {
            connectSocket();
        } , 1000);
    });
}
connectSocket();
